<!--策略启动-合约自定义-->
<template>
  <div class="bg bg1" @viewappear="viewappear" @viewdisappear="viewdisappear">

    <!--内容-->
    <scroller class="scroller">
      <div class="wrapper" v-if="isCopyShow">

        <!--服务器-->
        <VServer class="server" ref="server"></VServer>

        <!--Api-->
        <VCApi class="api" ref="upApi" v-model="api" :copyPair="copyPair"
        @apiChange="apiChange" @apiMoneyChange="apiMoneyChange"></VCApi>

        <div v-if="isShow">
          <!--交易对-->
          <VCPair class="pair" ref="pair" :pairMap="pairMap" @pairClick="pairClick"></VCPair>

          <!--策略方向-->
          <VCTarget class="target" ref="VCTarget" v-if="showTarget" :target="target" @targetClick="targetClick"></VCTarget>

          <!--信号-->
          <VSignal class="signal" ref="signal" v-model="signal" />

          <!--参数设置--> 
          <VParam class="server" ref="VParam" v-model="senior" 
          :reserves="configMap.reserves" :pairMap="pairMap" 
          :investCoin="investCoin" @paramChange="paramChange"></VParam>
          
          <!--杠杠倍率-->
          <div class="line bg3" v-if="senior"></div>
          <div class="seesaw" v-if="senior">
            <text class="font28 text2">{{T('杠杆倍数')}}</text>
            <div class="seesaw-but-hg">
              <div :class="['seesaw-but', leverRate == item ? 'main1' : 'bg2']" @click="leverClick(item)" v-for="(item, index) in leverRates" v-bind:key="index">
                <text class="font24 text1">{{item+'x'}}</text>
              </div>
            </div>
          </div>

          <!--投入资金-->
          <div class="invest" v-if="senior">
            <LInput class="input"  v-model="investNum" :title="T('总投入资金')" :limits="(T('范围')+minInvest+'~'+maxInvest)" :tips="T('总投入资金')" :unit="investCoin" @input="onInput"></LInput>
            
            <WeexSlideBar1 class="slide" ref='WeexSlideBar' @slideChange="slideChange"></WeexSlideBar1>

            <div class="row money">
              <text class="font24 text3">{{T('可用')+' '+moneyNum+' '+investCoin}}</text>
              <div class="row" @click="transferClick" v-if="api.apiId.length">
                <LImage class="transfer" :src="Config.img('huazhuan1.png')"></LImage>
                <text class="font24 main-t1">{{T('划转')}}</text>
              </div>
              <div class="all"></div>
            </div>
            <div class="row money">
              <text class="font24 text3" v-if="proposeInvest.length">{{T('建议投入')+' '+proposeInvest+' '+investCoin}}</text>
            </div>

            <div class="height40"></div>
            <text class="font24 text2 tipe">{{T('此策略为全仓模式，剩余未使用资金将自动划转至币币或资金账户。')}}</text>
          </div>

          <!--仓位风控-->
          <VCRisk class="control" ref="risk" v-model="risk"></VCRisk>
          
          <!--其他设置-->
          <VCSet class="set" ref="upSet" v-model="other" :stopProfit="stopProfit" :stopLoss="stopLoss" :timeStopStamp ="timeStopStamp"></VCSet>

          <!--跟单设置-->
          <div v-if="other">
            <div class="line bg3"></div>
            <VFollow class="follow" ref="follow" v-model="follows" 
            :type="'define'" :name="strategyName" :params="configMap.reserves" :investCoin="investCoin" :investNum="investNum" 
            :pairMap="pairMap" :commissionMap="commissionMap" :limitMap="{'minInvest':'100', 'maxInvest':'5000'}"></VFollow>
          </div>

          <div class="height80"></div>
        </div>
      </div>
    </scroller>

    <!--启动-->
    <div class="up bg3" v-if="api">
      <div :class="['up-but', (this.highVip && this.userOpenContract && api.apiId.length)  ? 'main1' : 'no1']" @click="upClick">
        <text class="font32 text1">{{getButTitle()}}</text>
      </div>
    </div>
  </div>
</template>

<script>

//组件
import VServer from "@/up/view/VServer.vue";
import VCApi from "@/upContract/view/VCApi.vue";
import VCPair from "@/upContract/view/VCPair.vue";
import VCTarget from "@/upContract/view/VCTarget.vue";
import VCRisk from "@/upContract/view/VCRisk.vue";
import VCSet from "@/upContract/view/VCSet.vue";
import VFollow from "@/up/view/VFollow.vue";
import VSignal from "@/up/view/VSignal.vue";

import VParam from "@/up/view/VParam.vue";
import LInput from "@/public/view/LInput.vue";
import UpFollow from "@/strategy/view/UpFollow.vue";

//功能
import navigator from "@/_js/navigator"; 
import modal from "@/_js/modal";
import math from "@/_js/math";
import broadcast from "@/_js/broadcast";
import Config from "@/_js/config";
import API from "@/_js/api";
import amContract from "@/upContract/amContract";
import amCopy from '@/up/amCopy'

const globalEvent = weex.requireModule('globalEvent');
import weexHttp from "@/_js/https"; ;
const weexFunction = weex.requireModule("WeexFunction");


import I18N from "@/_i18n/i18n";
var T = I18N.t;

export default {

  components: {
    VServer,
    VCApi,
    VCPair,
    VCTarget,
    VCRisk,
    VSignal,
    VParam,

    LInput,
    VCSet,
    UpFollow,
    VFollow,
  },

  props:{
    strategyId: String, //策略id
    strategyName: String, //策略名称
    showTarget:{ //显示策略方向
      type:Boolean,
      default:true,
    },
  },

  data() {
    return {
      T:T,
      Config:Config,
      math:math,
      appearRefresh:false, //turn 即将显示刷新
      isShow:false,

      paramExplain:{//0 做多 1 做空， 2双向
      "追投间隔":{'0':T('做多时只有在行情价≤上一次投入价格 *（1-追投间隔）时，才再次触发追踪买入开仓'), 
                '1':T('做空时只有在行情价≥上一次投入价格 *（1+追投间隔）时，才再次触发追踪卖出开仓'), 
                '2':T('做多时只有在行情价≤上一次投入价格 *（1-追投间隔）时，才再次触发追踪买入开仓；做空时只有在行情价≥上一次投入价格 *（1+追投间隔）时，才再次触发追踪卖出开仓')},

      "追投反弹":{'0':T('做多时触发追踪买入后从价格低点反弹此比例时立即买入开仓'), 
                '1':T('做空时触发追踪卖出后从价格高点回落此比例时立即卖出开仓'), 
                '2':T('做多时触发追踪买入后从价格低点反弹此比例时立即买入开仓；做空时触发追踪卖出后从价格高点回落此比例时立即卖出开仓')},
      
      "止盈阈值":{'0':T('做多时只有在行情价≥持仓均价 *（1+止盈阈值）时，才触发追踪止盈'), 
                '1':T('做空时只有在行情价≤持仓均价 *（1-止盈阈值）时，才触发追踪止盈'), 
                '2':T('做多时只有在行情价≥持仓均价 *（1+止盈阈值）时，才触发追踪止盈；做空时只有在行情价≤持仓均价 *（1-止盈阈值）时，才触发追踪止盈')},
      
      "止盈回撤":{'0':T('做多时触发追踪止盈后从价格高点回落此比例后即卖出平仓'), 
                '1':T('做空时触发追踪止盈后从价格低点回升此比例后即买入平仓'), 
                '2':T('做多时触发追踪止盈后从价格高点回落此比例后即卖出平仓；做空时触发追踪止盈后从价格低点回升此比例后即买入平仓')}},
      userOpenContract:false, //turn 开通合约权限
      highVip:false, //turn 累计开通3个月VIP，且当前是VIP

      api:undefined, //API
      counterCoin:undefined, //交易币
      baseCoin:undefined, //本币
      
      pairMap:undefined, //交易对
      configMap:undefined, //参数
      leverRates:[1, 2, 3, 5, 10],
      leverRatesx:[5, 10, 20, 30, 50],
      limitMap:undefined, //投入限制

      investCoin:'USDT', //投资币
      investNum:'', //总投入数量
      moneyNum:'', //可用数量
      proposeInvest:'', //建议投入
      leverRate:3, //杠杆

      isUp:false, //turn已经启动过这个交易对-可用为0

      /************************************ 跟单*/
      commissionMap:undefined, //跟单佣金
      follows:undefined, //跟单设置

      /************************************ 切换选中*/
      target: 0, //0 做多 1 做空， 2双向
      senior: true, //true 显示高级设置
      risk: true, //true 仓位风控
      other: false, //true 显示其他设置

      /************************************ 运算结果*/
      maxInvest: undefined, //最大投入
      minInvest: undefined, //最小投入


      /************************************ 复制配置*/
      copyPair: undefined, //交易对
      copyReserves: undefined, //参数数组
      stopProfit:'', //其他设置
      topLoss:'',
      timeStopStamp:'',
      isCopyShow:false,
    };
  },

  mounted() {

    /*处理直接跳转显示，传参*/
    var strategyId = navigator.getParam("strategyId");
    var strategyName = navigator.getParam("strategyName");
    var showTarget = navigator.getParam("showTarget");
    this.strategyId = strategyId ? strategyId : this.strategyId;
    this.strategyName = strategyName ? strategyName : this.strategyName;
    this.showTarget = showTarget != null ? showTarget : this.showTarget;


    //复制配置
    var copyConfig = navigator.getParam("copyConfig");
    var data = amCopy.getCopyData(copyConfig);
    if (data) {
      this.copyPair = data.copyPair;
      this.leverRate = this.copyPair.leverRate;
      this.target = this.copyPair.investType;
      this.copyReserves = data.copyReserves;

      var copySets = data.copySets;
      this.stopProfit = copySets.stopProfit;
      this.stopLoss = copySets.stopLoss;
      this.timeStopStamp = copySets.timeStopStamp;
    }
    this.isCopyShow =true;
  },

  methods: {

    /*************************************************通信触发*/
    //完全显示
    viewappear() {
      if (this.appearRefresh) {
        this.appearRefresh = false;
        this.httpQueryContractPermission();
      }
      this.$refs.pair && this.$refs.pair.viewappear();
    },

    //完全隐藏
    viewdisappear() {
      this.$refs.pair && this.$refs.pair.viewdisappear();
    },

    /**********************************************初始化数据*/
    //初始化基础数据
    initBasicsData(){
      
      this.senior = true; //true 显示高级设置
      this.other = false; //true 显示其他设置
    },

    //初始运算数据
    initData() {

      this.target = this.copyPair ? this.target : 0; //投入方向
      this.leverRate = this.copyPair ? this.leverRate : 3; //杠杆
      this.investNum = ''; //投入数量
      this.upInvestLimit(); //更新投入限制
      this.upApiMoney(); //更新可用余额
      setTimeout(() => { //延时0.1秒，不然未绘制滑条
        this.upSlideBar(); //更新滑条
      }, 100);
    },

    //刷新视图
    refreshView(){
      this.$refs.upSet && this.$refs.upSet.refresh(); 
    },

    /********************************************** https*/
    //查询合约权限
    httpQueryContractPermission(){

      modal.showLoad();
      var param = {'contractType':'contract_usdt'};
      weexHttp.post("contract/queryContractPermission",param,true,(data)=>{
        if(data.status == 200){
          data = data.data;
          this.highVip = data.highVip;
          this.userOpenContract = data.userOpenContract;

          if (!this.highVip) {
            this.opVip(true);
          }  else if (!this.userOpenContract) {
            this.opContract(true);
          } else  if (this.api.apiId == '') {
            this.addApi(true);
          }
          this.httpContractDefine()
        } else {
          modal.hideLoad();
          modal.toast(data.msg);
        }
      });
    },
    
    //http策略-合约自定义
    httpContractDefine(){

      this.isUp = false;
      var param = {'strategyId':this.strategyId, 
                   'contractType':'contract_usdt',
                   'exchangeId':this.api.exchangeId, 
                   'exchangeName':this.api.exchangeName, 
                   'counterCoin':this.counterCoin, 
                   'baseCoin':this.baseCoin};
      weexHttp.post("contract/defineStartPage",param,true,(data)=>{
        modal.hideLoad();
        if(data.status == 200){
          data = data.data;
          this.commissionMap = data.commissionMap;

          this.limitMap = data.limitMap;
          this.configMap = data.configMap;
          this.pairMap = data.pairMap;
          this.pairMap['baseCoinUsdPrice'] =  math.chu(this.pairMap.usdPrice, this.pairMap.last, math.getNumber(this.pairMap.baseCoinDecimal));

          this.pairMap.baseCoinUsdPrice = '1';
          this.pairMap.usdPrice = '1';
          this.pairMap.baseCoinDecimal = '4';
          this.pairMap.counterCoinDecimal = '4';

          //复制参数，直接使用不用计算
          if (this.copyReserves) {
            this.configMap.reserves = this.copyReserves;
          } else {

            for (let index = 0; index < this.configMap.reserves.length; index++) {
              var param = this.configMap.reserves[index];
              if (param.name == '单格投入（张）' || param.name == '首单投入（张）') {
                
                var value = T('当前合约面值 1张 = ') + math.xiaoShuDelete0(this.pairMap.contractSize) + ' ' + this.pairMap.counterCoin;
                param.comment = T(param.comment) + value;

                var start = math.cheng(this.pairMap.contractSize, this.pairMap.last);
                start = math.chu('8', start);
                start = math.xiaoshu(start, 0, 4);
                param.start = start;
                param.end = math.cheng(start, param.end, 0, 2);

                param.value = Number(param.value) < Number(start) ? start : param.value;
              }
            }

            for (let index = 0; index < this.configMap.reserves.length; index++) {
              var param = this.configMap.reserves[index];
              if (param.name == '网格间隔(等比)') {
                var value = {'name':'网格分布', 'value':0};
                this.configMap.reserves.splice(index, 0, value);
                break;
              }
            }
          }


          //交易对改变：保存API默认配置
          if (this.counterCoin != this.pairMap.counterCoin || this.baseCoin != this.pairMap.baseCoin) {
            this.counterCoin = this.pairMap.counterCoin;
            this.baseCoin = this.pairMap.baseCoin;
            this.setDefaultApi();
          }
          this.initBasicsData();
          this.initData();
          this.targetClick(this.target, true);
          this.refreshView();
          this.httpCheckContract();
          this.isShow = true;
          
          API.synchroCoinContract(this.api.apiId, this.pairMap.contractId, 'contract_usdt');
        } else {
          modal.toast(data.msg);
        }
      });
    },

    //http策略-启动过的合约编码
    httpCheckContract(){
      if (!this.highVip) {
        return;
      } else if (!this.userOpenContract) {
        return;
      } else if (this.api.apiId == '') {
        return;
      }

      var param = {'apiId':this.api.apiId,  
                   'contractType':'contract_usdt',
                   'exchangeName':this.api.exchangeName};
      weexHttp.post("contract/checkContract",param,true,(data)=>{
        if(data.status == 200){
          var data = data.data;

          //Bianca、OkexV5单账户只支持一个策略
          if (this.api.exchangeName.toLowerCase() == 'binance' ||
              this.api.exchangeName.toLowerCase() == 'okexv5' || exchangeName == 'gate') {

            if (data.executeList.length > 0) {
              this.isUp = true;
              this.tipeUpCoin();
            } else {
              this.isUp = false;
            }
            return;
          }

          var executes = JSON.stringify(data.executeList);
          if (executes.indexOf(this.pairMap.contractId) != -1) {
            this.isUp = true;
            this.tipeUpCoin();
          } else {
            this.isUp = false;
          }
        } else {            
          this.isUp = false;
        }
      });
    },

    /********************************** 其他方法*/

    /********************************** 改变*/
    //API改变
    apiChange(counterCoin, baseCoin){
      
      if (counterCoin && baseCoin) {
        this.counterCoin = counterCoin;
        this.baseCoin = baseCoin;
        this.httpQueryContractPermission();
      } else {
        modal.showLoad();
        this.httpContractDefine();
      }
    },

    //API资产改变
    apiMoneyChange(){
      
      var endStr = math.getNumber(this.maxInvest) > math.getNumber(this.moneyNum) ? this.moneyNum : this.maxInvest;
      if (math.getNumber(this.investNum) > math.getNumber(endStr)) {
        this.investNum = endStr;
      }
      this.upApiMoney();
      this.upSlideBar();
    },

    //交易对改变
    parChange(counterCoin, baseCoin){

      if (this.counterCoin == counterCoin && this.baseCoin == baseCoin ) {
        return;
      }
      this.counterCoin = counterCoin;
      this.baseCoin = baseCoin;
      this.setDefaultApi();
      modal.showLoad();
      this.httpContractDefine();
    },

    /********************************** 更新*/
    //更新Api默认配置
    setDefaultApi() {
      this.$refs.upApi.setDefaultApi(this.api.apiId, this.counterCoin, this.baseCoin);
    },

    //更新投入限制
    upInvestLimit() {
      
      //保留位数
      var xiaoshu = this.getXiaoshu();

      //默认投入范围
      var minInvest = this.limitMap.minInvest;
      var maxInvest = this.limitMap.maxInvest;
      this.proposeInvest = ''; 

      var contractSize = math.xiaoShuDelete0(this.pairMap.contractSize); //合约面值
      var last = this.pairMap.last; //当前价
      var lever = this.leverRate; //杠杆倍率

      //投入限制运算 (单格投入 or 首单投入)*合约面值*当前价/杠杆
      var investLimit = (onInvest)=>{
        var value = math.cheng(onInvest, contractSize);
        value = math.cheng(value, last);
        value = math.chu(value, lever, xiaoshu, 2);
        minInvest = Number(minInvest) > Number(value) ? minInvest : value;
        this.minInvest = Number(maxInvest) > Number(minInvest) ? minInvest : maxInvest;
        this.maxInvest = maxInvest;
      };

      //建议投入
      var investPropose = (propose)=>{

        if (math.getNumber(propose) < math.getNumber(this.minInvest)) {
          this.proposeInvest = this.minInvest;
        } else if (math.getNumber(propose) > math.getNumber(this.maxInvest)) {
          this.proposeInvest = this.maxInvest;
        } else {
          this.proposeInvest = propose;
        }
      };

      //合约网格
      if (this.strategyId == 'WL202007311426363424x') {
        var onInvest = this.getParam('单格投入（张）'); //单格投入
        investLimit(onInvest);
        if (onOrder == undefined) {
          investPropose('0');
          return;
        }
        
        //建议投入：(最大做多单数 + 最大做空单数) * 单格投入（张） * 合约面值 * 当前价 / 杠杆
        var many = this.getParam('最大做多单数');
        var empty = this.getParam('最大做空单数');
        var propose;
        if (this.target == 0) {
          propose = many;
        } else if (this.target == 1) {
          propose = empty;
        } else {
          propose = math.jia(many, empty); 
        }
        propose = math.cheng(propose, onInvest); // *单格投入
        propose = math.cheng(propose, contractSize); // *合约面值
        propose = math.cheng(propose, last); // *当前价
        propose = math.chu(propose, lever, xiaoshu, 2); // /杠杆
        investPropose(propose);
      } 

      //马丁追踪
      else if (this.strategyId == 'WL202007311426363425x') {
        var onOrder = this.getParam('首单投入（张）');
        investLimit(onOrder);
        if (onOrder == undefined) {
          investPropose('0');
          return;
        }

        var multiple = this.getParam('追投倍数');
        var maxOrder = this.getParam('最大做单数');
        if (multiple == undefined || maxOrder == undefined) {
          investPropose('0');
          return;
        }

        //建议投入
        //2^4 - 1 = 15 * 1 * 0.01 * 56930 * / 1
        //单向：(追投倍数^最大做单数-1）* 首单投入 * 合约面值 * 当前价/杠杆
        //双向：(追投倍数^最大做单数-1）* 2 * 首单投入 * 合约面值 * 当前价/杠杆
        var propose = Math.pow(multiple, Number(maxOrder)) - 1;
        if (this.target == 2) propose = math.cheng(propose, '2');
        propose = math.cheng(propose, onOrder); // *首单投入
        propose = math.cheng(propose, contractSize); // *合约面值
        propose = math.cheng(propose, last); // *当前价
        propose = math.chu(propose, lever); // /杠杠
        investPropose(propose);
      }

      //合约DCA
      else if (this.strategyId == 'WL20210624182847743') {
        var onOrder = this.getParam('首单投入');
        investLimit(onOrder);
        if (onOrder == undefined) {
          investPropose('0');
          return;
        }

        //最大做单数 = max（最大做多单数，最大做空单数）
        var maxOrder1 = this.getParam('最大做多单数');
        var maxOrder0 = this.getParam('最大做空单数');
        var maxOrder;
        if (this.target == 0 && maxOrder1 != undefined) {
          maxOrder =  maxOrder1;
        } else if (this.target == 1 && maxOrder0 != undefined) {
          maxOrder =  maxOrder0;
        } else if (maxOrder1 != undefined && maxOrder0 != undefined) {
          maxOrder = Number(maxOrder1) > Number(maxOrder0) ? maxOrder1 : maxOrder0;
        }

        var type = this.getParam('补仓金额模式');
        if (type == undefined || maxOrder == undefined) {
          investPropose('0');
          return;
        }
        
        // 建议投入：补仓金额模式
        // 倍数补仓（补仓金额模式0）：
        // 1、补仓金额倍数≠1：【（补仓金额倍数^最大做单数-1）/（补仓金额倍数-1）】*首单投入*合约面值*当前价/杠杆
        // 2、补仓金额倍数＝1：最大做单数*首单投入*合约面值*当前价/杠杆
        // 增量补仓（补仓金额模式1）：【最大做单数 * 首单投入 +（最大做单数^2-最大做单数）* 补仓金额增量/2】*合约面值*当前价/杠杆
        // 其中此处 
        if(type == 0) {
          var multiple = this.getParam('补仓金额倍数');
          if (multiple == undefined) {
            investPropose('0');
            return;
          }
          
          var propose;
          if (multiple == 1) {
            //2、补仓金额倍数＝1：最大做单数
            propose = maxOrder;
          } else {
            //1、补仓金额倍数≠1：【（补仓金额倍数^最大做单数-1）/（补仓金额倍数-1）】
            var _multiple = math.jian(multiple, '1');
            propose = Math.pow(Number(multiple), Number(maxOrder)) - 1;
            propose = math.chu(propose, _multiple);
          }

          //*首单投入
          propose = math.cheng(propose, onOrder);

        } else {
          
          //增量补仓（补仓金额模式1）：【最大做单数 * 首单投入 +（最大做单数^2-最大做单数）* 补仓金额增量/2】
          var bulking = this.getParam('补仓金额增量');
          if (bulking == undefined) {
            investPropose('0');
            return;
          }
          var _propose = math.cheng(maxOrder, onOrder);
          propose = Math.pow(Number(maxOrder), 2) - maxOrder;
          propose = math.cheng(propose, bulking);
          propose = math.chu(propose, '2');
          propose = math.jia(_propose, propose);
        }
        //*合约面值*当前价/杠杆
        propose = math.cheng(propose, contractSize);
        propose = math.cheng(propose, last);
        propose = math.chu(propose, lever, xiaoshu, 2);
        investPropose(propose);
      }
      
      else {
        this.minInvest = '100';
        this.maxInvest = '100000';
      }
    },
    
    //更新滑条
    upSlideBar(){

      var starStr = '0';
      var endStr = math.getNumber(this.maxInvest) > math.getNumber(this.moneyNum) ? this.moneyNum : this.maxInvest;
      endStr = endStr +'';
      
      var ratio = this.investNum.length ? math.chu(this.investNum, endStr, 2, 2) : '0';
      ratio = math.getNumber(ratio) > 1 ? '1' : ratio;
      ratio = math.getNumber(endStr) == 0 ? 0 : ratio;

      var a = {'starStr':starStr, 'endStr':endStr, 'ratio':ratio};
      
      this.$refs.WeexSlideBar.upSlide(a);
    },

    //更新可用数量
    upApiMoney() {
      
      //保留位数
      var xiaoshu = this.getXiaoshu();
      
      var exchangeName = this.api.exchangeName.toLowerCase();
      var coin = API.isExchangeUSDT(exchangeName) ? this.investCoin : this.counterCoin;
      var num =  '0';
      if (this.api.apiId == '') {
        num = this.maxInvest;
      } else {
        for (let index = 0; index < this.api.linerSwapAssets.length; index++) {
          var assets = this.api.linerSwapAssets[index];
          if (assets.currency == coin) {
            num = math.xiaoshu(assets.withdrawAvailable, xiaoshu, 2);
            break;
          }
        }
      }
      this.moneyNum = math.getNumber(num) < 0 ? '0' : num;
    },
    
    /********************************** GET*/
    //获取按钮标题
    getButTitle() {
      
      if (!this.highVip) {
        return T('开通会员');
      } else if (!this.userOpenContract) {
        return T('开通合约权限');
      } else if (this.api.apiId == '') {
        return T('录入API');
      } else {
        return T('启动');
      }
    },

    //获取保留小数位
    getXiaoshu() {
      var xiaoshu = this.target ? this.pairMap.counterCoinDecimal : this.pairMap.baseCoinDecimal;
      xiaoshu = math.getNumber(xiaoshu);
      return xiaoshu;
    },

    //获取参数
    getParam(name){

      var value;
      var reserves = this.$refs.VParam ? this.$refs.VParam.getParam() : this.configMap.reserves;
      for (let index = 0; index < reserves.length; index++) {
        var param = reserves[index];
        if (param.name == name) {
          value = param.value;
          break;
        }
      }
      value =  value ? value : null;
      return value;
    },
    
    /********************************** 代理回调*/
    //总投入资金-输入改变
    onInput(e){
      this.upSlideBar();
    },

    //滑动条-滑动改变
    slideChange(e) {

      var ratio = e.ratio;
      var endStr = math.getNumber(this.maxInvest) > math.getNumber(this.moneyNum) ? this.moneyNum : this.maxInvest;
      if (math.getNumber(endStr) == 0) {
        this.investNum = '0';
        return;
      }

      //保留位数
      var xiaoshu = this.getXiaoshu();
      this.investNum = math.cheng(endStr, ratio, xiaoshu, 2);
    },
    
    //参数值改变-回调
    paramChange(){
      this.upInvestLimit();
    },

    /********************************** 点击触发*/
    //启动了策略
    upStrategy() {
      var tipe = T("单个统一账户只支持一个合约策略且执行币币策略时不可执行合约策略，&{1}账户已有执行中的策略，您可前往执行列表查看").replace("&{1}", this.api.apiName);
      var parm = {'message':tipe};
      modal.alert(parm, (bool)=>{
      });
    },

    //开通VIP
    opVip(tipe) {

      var op = ()=>{
        // this.appearRefresh = true;
        weexFunction.buyVip(1, (flag)=>{
          this.appearRefresh = false;
          this.httpQueryContractPermission();
        });
      };

      if (!tipe) {
        op();
        return;
      }

      var parm = {'title':T("暂无权限"),
                'message':T("很抱歉，为保证高频交易质量，此策略仅对会员用户开放。"),
                'okBtn':T("开通会员"), 'cancelBtn':T("取消")};
      modal.confirm(parm, (bool)=>{
        (bool == "true") ? op() : navigator.back();
      });
    },

    //开通合约
    opContract(tipe) {

      var op = ()=>{
        this.appearRefresh = true;
        navigator.open('', 'upContract/COp');
      };

      if (!tipe) {
        op();
        return;
      }

      var parm = {'title':T("开通合约策略"),
                  'message':T("很抱歉，您尚未开通合约策略交易功能，暂不能使用此策略。"),
                  'okBtn':T("开通合约策略"), 'cancelBtn':T("取消")};
      modal.confirm(parm, (bool)=>{
        (bool == "true") ? op() : navigator.back();
      });
    },

    //录入API
    addApi(tipe) {

      var add = ()=>{
        this.appearRefresh = true;
        var nav = {'navColor':'#0c0c0c'};
        navigator.open('', 'home/ApiAdd', undefined, nav);
      };

      if (!tipe) {
        add();
        return;
      }

      if(this.copyPair) {
        var parm = {message:T("很抱歉，您没有 &{1} API,请录入或者切换其他交易所API。").replace("&{1}", this.copyPair.exchangeName),
                  okBtn:T("录入API"), cancelBtn:T("知道了")};
        modal.confirm(parm, (bool)=>{
          (bool == "true") ? add() : '';
        });
        return;
      }
      
      var exchanges = this.$refs.upApi ? this.$refs.upApi.exchanges : ['Binance'];
      var str = ''
      for (let index = 0; index < exchanges.length; index++) {
        var exchange = exchanges[index];
        str += str.length ? '、' : '';
        str += exchange;
      }
      var parm = {message:T("很抱歉，暂时只支持&{1}合约策略交易。请录入对应交易所API，并确保已在交易所开通USDT本位合约功能。").replace("&{1}", str),
                  okBtn:T("录入API"), cancelBtn:T("取消")};
      modal.confirm(parm, (bool)=>{
        (bool == "true") ? add() : navigator.back();
      });
    },
    
    //提示启动过该币种
    tipeUpCoin(){
      
      var tipe;
      if  (this.api.exchangeName.toLowerCase() == 'binance') {
        tipe = T('单个Binance账户只支持执行一个合约策略，&{1}账户已有执行中的合约策略，您可前往执行列表查看。');
      } else if (this.api.exchangeName.toLowerCase() == 'okexv5') {
        tipe = T('单个统一账户只支持一个合约策略且执行币币策略或托管项目时不可执行合约策略，&{1}账户已有执行中的策略或托管项目，您可前往执行列表查看。');
      } else {
        tipe = T('单个合约品种只支持执行一个策略，&{1}账户【&{2}】已有执行中的合约策略，您可前往执行列表查看。');
      }
      tipe = tipe.replace("&{1}", this.api.apiName);
      tipe = tipe.replace("&{2}", this.counterCoin + T('永续') + '/' + this.baseCoin);
      modal.alert(tipe,()=>{
      });
    },
    
    //交易对
    pairClick(){
      
      var param = {exchangeId:this.api.exchangeId,
                  counterCoin:this.pairMap.counterCoin,
                  baseCoin:this.pairMap.baseCoin};
      navigator.open('', 'upContract/CSelectPair', param);

      broadcast.subscribeOnce('CSelectPair', (pairMap)=>{
        this.parChange(pairMap.counterCoin, pairMap.baseCoin);
      });
    },

    //策略方向 - 重置参数
    targetClick(target, http){
      this.target = target;

      var reserves = JSON.parse(JSON.stringify(this.configMap.reserves));

      ////0 做多 1 做空， 2双向
      for (let index = 0; index < reserves.length; index++) {
        var param = reserves[index];
        if (param.name == '最大做多单数') {
          param.visiable = target != 1 ? '1' : '0';
        } else if (param.name == '最大做空单数') {
          param.visiable = target != 0 ? '1' : '0';
        }

        //特殊参数-不同方向不同解释
        var dict = this.paramExplain[param.name];
        if (dict) {
          var key = target + '';
          var comment = dict[key];
          param.comment = comment;
        }
      }
      

      this.configMap.reserves = reserves;
      this.upInvestLimit();
    },

    //杠杆倍数
    leverClick(item) { 
      this.leverRate = item;
      this.upInvestLimit();
    },

    //划转
    transferClick() {
      
      var nav = {'navColor':'#0c0c0c'};
      var param = {'apiId':this.api.apiId, 'pairMap':this.pairMap};
      if (this.api.exchangeName.toLowerCase() == 'okexv5') {
        navigator.open('', 'home/ApiTransferV5', param, nav);
      } else {
        navigator.open('', 'home/ApiTransfer', param, nav);
      }
    },

    //启动
    upClick() {
      
      //开通VIP
      if (!this.highVip) {
        this.opVip(false);
        return;
      }
      
      //开通权限
      if (!this.userOpenContract) {
        this.opContract(false);
        return;
      }
      
      //录入API
      if (this.api.apiId == ''){
        this.addApi(false);
        return;
      }

      //服务器检查
      if (this.$refs.server && this.$refs.server.checkError()) {
        return;
      }
      
      //重复启动相同币种
      if (this.isUp) {
        this.tipeUpCoin();
        return;
      }
      
      //信号设置
      if (this.$refs.signal.checkError()) {
        return;
      }

      //高级设置
      if (this.$refs.VParam.checkError()) {
        return;
      }

      //投入资金-测试
      if (this.investNum.length == 0) {
        modal.toast(T("请输总投入资金"));
        return;
      }
      
      if (math.getNumber(this.investNum) == 0) {
        modal.toast(T("总投入资金不可为0"));
        return;
      }

      if (math.getNumber(this.investNum) < math.getNumber(this.minInvest)) {
        modal.toast(T("总投入资金不可低于") + this.minInvest + this.investCoin);
        return;
      }
      
      if (math.getNumber(this.investNum) > math.getNumber(this.maxInvest)) {
        modal.toast(T("总投入资金不可高于") + this.maxInvest + this.investCoin);
        return;
      }

      if (math.getNumber(this.investNum) > math.getNumber(this.moneyNum)) {
        modal.toast(T("可用余额不足"));
        return;
      }
      
      //仓位风控
      if (this.$refs.risk.checkError()) {
        return;
      }

      //其他设置
      if (this.$refs.upSet.checkError()) {
        return;
      }

      var executeConfig = JSON.parse(JSON.stringify(this.configMap));
      var signal =  this.$refs.signal.getParam(); 
      var reserves =  this.$refs.VParam.getParam(); 
      var riskMap = this.$refs.risk.getParam(); 
      var setMap = this.$refs.upSet.getParam(); 

      var isOpenFollow = this.follows ? this.follows.isFollow : true;
      var followMap = this.follows ? this.follows.followMap : undefined;
      
      var address = '';
      if (this.$refs.server) {
        var server =  this.$refs.server.server;
        address = server ? server.innerIp : '';
      }
      

      var param = {'address':address,
                  'api':this.api,
                  'strategyId':this.strategyId,
                  'investCoin':this.investCoin, 'investCoinnNum':this.investNum, 'leverRate':(this.leverRate+''),
                  'investType':this.target, 'startType':'OFFICIAL', 'contractType':'contract_usdt', 
                  'executeConfig':executeConfig, 'pairMap':this.pairMap,
                  'signal':signal, 'reserves':reserves, 'setMap':setMap, 'riskMap':riskMap, 
                  'isOpenFollow':isOpenFollow};
      if (followMap) param['followConfig'] = followMap;

      amContract.httpDefineUp(param,()=>{
        broadcast.send(broadcast.EXECUTE_UPDATE);
        navigator.back();
      });
    }
  }
}
</script>


<style src="@/_css/style.css"></style>
<style scoped>
.bg {
  width: 750px;
  flex: 1;
}
.explain{
  width: 28px;
  height: 28px;
  margin-left: 8px;
  margin-right: 8px;
}
.line{
  width: 710px;
  height: 2px;
  margin-top: 40px;
  margin-bottom: 40px;

  margin-left: 40px;
}
.signal {
  margin-top: 40px;
  margin-left: 40px;
  margin-right: 40px;
}
.server {
  margin-top: 40px;
  margin-left: 40px;
  margin-right: 40px;
}

.api{
  margin-top: 40px;
  margin-left: 80px;
  margin-right: 80px;
}

.pair{
  margin-top: 40px;
  margin-left: 40px;
}

.target{
  width: 670px;
  margin-left: 40px;
  margin-top: 40px;
}

.senior{
  width: 670px;
  margin-left: 40px;
  margin-top: 60px;
}

.seesaw {
  width: 670px;
  margin-left: 40px;
}
.seesaw-but-hg {
  flex-direction: row;
  justify-content: space-between;
  width: 670px;
  margin-top: 40px;
  margin-bottom: 40px;
}
.seesaw-but {
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: 122px;
  height: 76px;
  border-radius: 38px;
}
.seesawSlide {
  width: 670px;
  height:160px;
  margin-top: 20px;
}

.invest{
  margin-left: 40px;
  margin-bottom: 40px;
}
.input {
  margin-bottom: 0px;
}
.slide{
  width: 670px;
  height:160px;
  margin-top: 10px;
}
.money{
  width: 670px;
  margin-top: 20px;
  text-align: right;
}
.tipe{
  width: 670px;
}

.transfer{
  width: 28px;
  height: 28px;

  margin-left: 20px;
  margin-right: 12px;
}

.control {
  margin-top: 40px;
  margin-left: 40px;
}

.set{
  margin-top: 40px;
  margin-left: 40px;
}

.follow{
  margin-left: 40px;
  margin-right: 40px;
}

/*************** 选择按钮*/
.select {
  flex-direction: row;
  justify-content: space-between;
  width: 670;
}
.select-but {
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 76px;
  border-radius: 16px;
  margin-top: 20px;
}
/*************** 启动*/
.up{
  flex-direction: row;
  justify-content: center;
  width: 750px;
  height: 164px;

  border-radius: 8px;
}
.up-but{
  flex-direction: row;
  justify-content: center;
  align-items: center;
  width: 670px;
  height: 80px;
  border-radius: 4px;
  margin-top: 28px;
}

/*************** 宽高*/
.height40{
  height: 40px;
}
.height80{
  height: 80px;
}
.width300{
  width: 300px;
}
.width200{
  width: 200px;
}

</style>